package cn.wolfcode.luowowo.feign;

import cn.wolfcode.luowowo.SmsFeignApi;
import cn.wolfcode.luowowo.common.Result;
import cn.wolfcode.luowowo.msg.MsgCodeMsg;
import cn.wolfcode.luowowo.redis.RedisKeys;
import cn.wolfcode.luowowo.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by wolfcode-lanxw
 */
@RestController
public class SmsFeignClient implements SmsFeignApi {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Result sendVerifyCode(String phone) {
        //1:创建短信验证码
        String code = UUID.randomUUID().toString()
                .replaceAll("-", "").substring(0, 4);
        //2:拼接一个短信
        StringBuilder sb = new StringBuilder(80);
        sb.append("您好, 您的注册验证码是:").append(code).append("请在").append(Consts.VERIFY_CODE_VAI_TIME)
                .append("分钟之内使用");
        //3:发送短信 : 假装发一个短信
        System.out.println(sb.toString());
        String key = RedisKeys.VERIFY_CODE.join(phone);
        redisTemplate.opsForValue().set(key, code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
        return Result.success();
    }

    @Override
    public Result checkVerifyCode(String phone, String verifyCode) {
        if(StringUtils.isEmpty(phone)){
            return Result.error(MsgCodeMsg.PARAM_ERROR.fillArgs("手机号码格式不正确"));
        }
        if(StringUtils.isEmpty(verifyCode)){
            return Result.error(MsgCodeMsg.PARAM_ERROR.fillArgs("验证码不能为空"));
        }
        String key = RedisKeys.VERIFY_CODE.join(phone);
        String code = redisTemplate.opsForValue().get(key);
        if(code == null || !code.equalsIgnoreCase(verifyCode)){
            return Result.error(MsgCodeMsg.PARAM_ERROR.fillArgs("验证码失效或者错误"));
        }
        return Result.success();
    }
}
